package com.plusjun.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.plusjun.common.constant.AuthServerConstant;
import com.plusjun.common.utils.HttpUtils;
import com.plusjun.common.utils.R;
import com.plusjun.common.vo.MemberRespVO;
import com.plusjun.gulimall.auth.feign.MemberFeignService;
import com.plusjun.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@Slf4j
public class OAuth2Controller {
    @Value("${weibo.client_id}")
    private String client_id;

    @Value("${weibo.client_secret}")
    private String client_secret;

    @Value("${weibo.grant_type}")
    private String grant_type;

    @Value("${weibo.redirect_uri}")
    private String redirect_uri;

    @Resource
    private MemberFeignService memberFeignService;


    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session)  throws Exception {
        // 1、根据code获取accessToken
        Map<String, String> map = new HashMap<>();
        map.put("client_id", client_id);
        map.put("client_secret", client_secret);
        map.put("grant_type", grant_type);
        map.put("redirect_uri", redirect_uri);
        map.put("code", code);
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com",
                                            "/oauth2/access_token",
                                            "post", new HashMap<>(), map, new HashMap<>());

        // 2、处理响应结果
        if (response.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            // 知道了是哪个社交账号,调用远程服务进行登录
            R r = memberFeignService.oauthLogin(socialUser);
            if (r.getCode() == 0) {
                MemberRespVO memberRespVO = (MemberRespVO) r.getData(new TypeReference<MemberRespVO>() {
                });
                log.info("用户：{} 登录成功 O(∩_∩)O",memberRespVO);
                // 默认发的令牌。session=xxxx。作用域：当前域
                // 使用JSON的序列化方式来序列化对象数据到redis中
                session.setAttribute(AuthServerConstant.LOGIN_USER,memberRespVO);
                // 3、成功后重定向到首页
                return "redirect:http://gulimall.com";

            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }


        } else {
            // 响应状态码不是200，则登录失败
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
